package com.trendit.classicpos.core;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

import com.trendit.classicpos.ClassicPosApp;
import com.trendit.classicpos.R;

import java.util.ArrayDeque;
import java.util.Queue;

public class KeyManager {

    //系统关机
    public static final int KEY_POWER = 0x01;

    public static final int KEY_F1 = 0x02;

    public static final int KEY_F2 = 0x03;

    public static final int KEY_F3 = 0x04;

    public static final int KEY_FUNCTION = 0x05;

    public static final int KEY_DIGITAL1 = 0x06;

    public static final int KEY_DIGITAL2 = 0x07;

    public static final int KEY_DIGITAL3 = 0x08;

    public static final int KEY_ALPHA = 0x09;

    public static final int KEY_DIGITAL4 = 0x0A;

    public static final int KEY_DIGITAL5 = 0x0B;

    public static final int KEY_DIGITAL6 = 0x0C;

    public static final int KEY_ESC = 0x0D;

    public static final int KEY_DIGITAL7 = 0x0E;

    public static final int KEY_DIGITAL8 = 0x0F;

    public static final int KEY_DIGITAL9 = 0x10;

    public static final int KEY_CLEAR = 0x11;

    public static final int KEY_UP_OR_10 = 0x12;

    public static final int KEY_DIGITAL0 = 0x13;

    public static final int KEY_DOWN_OR_11 = 0x14;

    public static final int KEY_ENTER = 0x15;

    public static final int KEY_POWERSHORT = 0x16;

    private Queue<Integer> keyQueue;
    private static KeyManager sInstance;
    private SoundPool mSoundPool;
    private int beep;

    private void initSoundPool(Context context) {
        synchronized (this) {
            if (mSoundPool == null) {
                mSoundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0);
                beep = mSoundPool.load(context, R.raw.beeper, 1);
            }
        }
    }

    private void releaseSoundPool() {
        synchronized (this) {
            if (mSoundPool != null) {
                mSoundPool.release();
                mSoundPool = null;
            }
        }
    }

    private void playSound(int sound) {
        synchronized (this) {
            if (mSoundPool == null) {
                return;
            }
            mSoundPool.play(sound, 1.0f, 1.0f, 0, 0, 1.0f);
        }
    }

    private KeyManager() {
        keyQueue = new ArrayDeque<>();
        initSoundPool(ClassicPosApp.getInstance());
    }

    public static KeyManager getsInstance() {
        if (sInstance == null) {
            sInstance = new KeyManager();
        }
        return sInstance;
    }

    public void clear() {
        keyQueue.clear();
    }

    public int poll() {
        Integer value = keyQueue.poll();
        return value == null ? 0 : value;
    }

    public void push(int key) {
        keyQueue.add(key);
    }

    public void beep() {
        playSound(beep);
    }

}
